from functools import wraps

def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunc():
        print("do somethins before a_func()")
        a_func()
        print("do somethins after a_func()")
    return wrapTheFunc
@a_new_decorator
def a_require_decorate_func():
    print("a_require_decorate_func")
# a_require_decorate_func()
# @wraps(a_func)
# print(a_require_decorate_func.__name__)
#a_require_decorate_func = a_new_decorator(a_require_decorate_func)
#a_require_decorate_func()

# 蓝本规范
# def decorator_name(f):
#     @wraps(f)
#     def decorated(*args, **kwargs):
#         # print(f.__name__ + " was called")
#         if not can_run:
#             return "func will not run"
#         return f(*args, **kwargs)
#     return decorated
#
# @decorator_name
# def func():
#     return "Function is running"
# can_run = True
# print(func())
# # Function is running
# can_run = False
# print(func())
# func will not run

# Flask 和 Django中授权
# from functools import wraps
# def requires_auth(f):
#     @wraps(f)
#     def decorated(*args, **kwargs):
#         auth = request.authorization
#         if not auth or not check_auth(auth.username, auth.password):
#             authenticate()
#         return f(*args, **kwargs)
#
#     return decorated

# 日志是装饰器运用的另一个亮点

# print()
# def logit(f):
#     @wraps(f)
#     def with_logging(*args, **kwargs):
#         print(f.__name__ + " was called")
#         return f(*args, **kwargs)
#     return with_logging
#
# @logit
# def add_func(x):
#     return x + x
# print(add_func(3))

def logit(logfile='out11.log'):
    def logging_decorater(func):
        @wraps(func)
        def with_logging(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 写入日志文件
            with open(logfile, 'a') as fs:
                fs.write(log_string + '\n')
            return func(*args, **kwargs)
        return with_logging
    return logging_decorater

@logit()
def myfunc1():
    pass
myfunc1()

@logit(logfile='out22.log')
def myfunc2():
    pass
myfunc2()
